//
//  SCLoginController.m
//  Scalper
//
//  Created by 王云 on 2017/9/27.
//  Copyright © 2017年 WY. All rights reserved.
//

#import "SCLoginController.h"
#import "RegViewController.h"
#import "SCFindController.h"
#import "HomeController.h"
#import "IdentitySViewController.h"
#import "SCLoginBindingController.h"

#import <UMSocialCore/UMSocialCore.h>
#import "WXApi.h"

#import "SCAboutController.h"
@interface SCLoginController ()<UITextFieldDelegate>

@end

@implementation SCLoginController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"登陆";
    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
    textAttrs[NSForegroundColorAttributeName] = [UIColor blackColor];
    textAttrs[NSFontAttributeName] = [UIFont systemFontOfSize:16];
    [self.navigationController.navigationBar setTitleTextAttributes:textAttrs];
    
    if (![WXApi isWXAppInstalled]) {
        _WXBtn.hidden = YES;
        _orImg.hidden = YES;
    }
    
    if (isIphone5) {
        _wxBottomLayout.constant = 0;
        _phoneTopLayout.constant = 8 ;
    }

    
    _WXBtn.tag = UMSocialPlatformType_WechatSession;
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"arrowleft" highIcon:@"" target:self action:@selector(pop)];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithIcon:@"login_help" highIcon:@"login_help" target:self action:@selector(help)];
    _PromptL.attributedText = [WYNSString Att:@"温馨提示:\n 1、微信公众号用户可直接点以上微信图标，来同步账号数据。请不要重新注册账号，否则原公众号数据将不能同步。\n2、已绑定手机号的黄牛派账号，可在本界面直接登录；如未设置或忘记登录密码，请点“忘记密码”来重设密码。" rang:@"温馨提示:" font:[UIFont systemFontOfSize:15] color:KOrange ParagraphSpacing:8];
    if ([[UIDevice currentDevice].model isEqualToString:@"iPad"]) {
        _PromptL.text = @"";
    }

}
- (void)pop{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)help{
    SCAboutController *ideaVC = [[SCAboutController alloc] init];
    ideaVC.type = @"HelpAccount";
    [self.navigationController pushViewController:ideaVC animated:YES];
}
- (IBAction)login:(id)sender {

    [self.view endEditing:YES];
    if (![HWCommon isMobileNumber:_phoneF.text]) {
        [SCTool showError:@"请输入正确手机号码"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [_phoneF becomeFirstResponder];
        });
        return;
    }
    
    if (_pwdF.text.length < 6) {
        [SCTool showError:@"密码输入过短"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [_pwdF becomeFirstResponder];
        });
        return;
    }
    [SCTool showLoading:@"正在登陆..."];
    __weak __typeof(&*self)weakSelf = self;
    [SCApiTool ScLoginMember_mobile:_phoneF.text member_passwd:_pwdF.text unionid:@"" headimgurl:@"" nickname:@"" sex:@"" success:^(NSString *msg) {
        
        [SCTool showSuccess:@"登录成功"];
        if ([[SCUserTool loadInfo].joinin_state isEqualToString:@"0"]) {
        
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                IdentitySViewController *identityVC = [[IdentitySViewController alloc] init];
                 [weakSelf.navigationController pushViewController:identityVC animated:YES];
                
            });
            
        }else{
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [UIApplication sharedApplication].keyWindow.rootViewController =[[JTNavigationController alloc] initWithRootViewController:[[HomeController alloc] init]]; ;
            });
        }
        
    } failure:^(NSString *errormsg) {
        
        [SCTool showError:errormsg];
    }];
}
- (IBAction)findPwd:(id)sender {
    
    SCFindController *findVC  = [[SCFindController alloc] init];
    [self.navigationController pushViewController:findVC animated:YES];
}
- (IBAction)regF:(id)sender {
    
    RegViewController *regVC = [[RegViewController alloc] init];
    [self.navigationController pushViewController:regVC animated:YES];
    
}


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if (textField == _phoneF){
        
        NSInteger existedLength = textField.text.length;
        NSInteger selectedLength = range.length;
        NSInteger replaceLength = string.length;
        if (existedLength - selectedLength + replaceLength > 11) {
            return NO;
        }
    }else if (textField == _pwdF){
        
        NSInteger existedLength = textField.text.length;
        NSInteger selectedLength = range.length;
        NSInteger replaceLength = string.length;
        if (existedLength - selectedLength + replaceLength > 20) {
            return NO;
        }
    }
    return YES;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    [self.navigationController.navigationBar lt_setBackgroundColor:[UIColor whiteColor]];

    self.navigationController.navigationBar.backgroundColor = [UIColor whiteColor];
    self.view.backgroundColor = [UIColor whiteColor];
   
}
- (IBAction)WXClick:(UIButton *)sender {
    
    UMSocialPlatformType snsNameType ;
    switch (sender.tag) {
        case UMSocialPlatformType_WechatSession:
        {
            snsNameType = UMSocialPlatformType_WechatSession;
            break;
        }
        default:{
            snsNameType = UMSocialPlatformType_WechatSession;
        }
            break;
    }
    __weak __typeof(&*self)weakSelf = self;
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:snsNameType currentViewController:self completion:^(id result, NSError *error) {
        
        if (error) {
            
        } else {
            UMSocialUserInfoResponse *resp = result;
            
            
            // 第三方登录数据(为空表示平台未提供)
            // 授权数据
            DLog(@" uid: %@", resp.uid);
            DLog(@" openid: %@", resp.openid);
//            NSLog(@" accessToken: %@", resp.accessToken);
//            NSLog(@" refreshToken: %@", resp.refreshToken);
//            NSLog(@" expiration: %@", resp.expiration);
            
            // 用户数据
            DLog(@" name: %@", resp.name);
            DLog(@" iconurl: %@", resp.iconurl);
            DLog(@" gender: %@", resp.unionGender);
            
            // 第三方平台SDK原始数据
            DLog(@" originalResponse: %@", resp.originalResponse);
            [weakSelf snsName:snsNameType snsAccount:resp];
            
        }
    }];
}
- (void)snsName:(UMSocialPlatformType )snsNameType snsAccount:(UMSocialUserInfoResponse *)snsAccount {
    if (snsNameType == UMSocialPlatformType_WechatSession){
        
        __weak __typeof(&*self)weakSelf = self;
         [SCTool showLoading:@"登录中"];
        [SCApiTool ScLoginMember_mobile:@"" member_passwd:@"" unionid:snsAccount.unionId headimgurl:snsAccount.iconurl nickname:snsAccount.name sex:snsAccount.unionGender success:^(NSString *msg) {
            
            [SCTool showSuccess:@"登录成功"];
            SCUser *user = [SCUserTool loadInfo];
            if (user.member_mobile_bind == 1) {
                
                if ([[SCUserTool loadInfo].joinin_state isEqualToString:@"0"]) {
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        
                        IdentitySViewController *identityVC = [[IdentitySViewController alloc] init];
                        [weakSelf.navigationController pushViewController:identityVC animated:YES];
                        
                    });
                    
                }else{
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [UIApplication sharedApplication].keyWindow.rootViewController =[[JTNavigationController alloc] initWithRootViewController:[[HomeController alloc] init]]; ;
                    });
                }

              
            }else{
                SCLoginBindingController *logBinVC = [[SCLoginBindingController alloc] init];
                logBinVC.unioid = snsAccount.unionId;
                [self.navigationController pushViewController:logBinVC animated:YES];
            }
            
            
        } failure:^(NSString *errormsg) {
            [SCTool showError:errormsg];
        }];
        
    }
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}


@end
